package com.linxz.ui.spraycarview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.SurfaceTexture;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.TextureView;

import androidx.annotation.Nullable;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.Observer;

import com.linxz.ui.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class SprayPaintCarView extends TextureView implements TextureView.SurfaceTextureListener{
    private int mWidth;
    private int mHeight;
    private static final int FLING_MIN_DISTANCE = 50;// 移动最小距离
    private static final int FLING_MIN_VELOCITX = 100;// 移动最大速度
    private Paint mPaint;
    private GestureDetector mGestureDetector;
    private int  mCurrentDirection=0;
    private List<CarDirection> mDirectionData=new ArrayList<>();
    private boolean inited=false;
    private HashMap<String,SprayItem2> sprayItems2=new HashMap<>();
    private SprayItemData data;
    private ExecutorService mExecutor;
    public SprayPaintCarView(Context context) {
        super(context);
        init();
    }

    public SprayPaintCarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public SprayPaintCarView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    private void init(){
        mPaint=new Paint();
        mGestureDetector=new GestureDetector(getContext(),mOnGestureListener);
        mExecutor=Executors.newSingleThreadExecutor();
        setSurfaceTextureListener(this);

    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
          // System.out.println("###onSurfaceTextureAvailable:"+width+" "+height);
        System.out.println("###onSurfaceTextureAvailable:"+width+" "+height);
        if(!inited){
            mWidth=width;
            mHeight=height;
            mDirectionData.add(new CarLeftFront());
            mDirectionData.add(new CarRightFront());
            mDirectionData.add(new CarRightRear());
            mDirectionData.add(new CarLeftRear());
            for(CarDirection direction:mDirectionData){
                direction.init(width,height);
            }
            inited=true;
        }
        showDirection(mCurrentDirection);
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
        System.out.println("###onSurfaceTextureSizeChanged:"+width+" "+height);
    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        System.out.println("###onSurfaceTextureDestroyed:");

        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {

    }




    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mGestureDetector.onTouchEvent(event);
        return true;
    }

    private GestureDetector.SimpleOnGestureListener mOnGestureListener=new GestureDetector.SimpleOnGestureListener(){
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            System.out.println("###单击:"+e.getX()+" "+e.getY());
            CarDirection direction=mDirectionData.get(mCurrentDirection);
            List<ICarPart> list=new ArrayList<>(direction);
            SprayItem2 itemAll=sprayItems2.get(Constant.ID_ALL);
            for(int i=list.size()-1;i>=0;i--){
                ICarPart part=list.get(i);
                if(part instanceof CarPart){
                    if(part.isInRect((int)e.getX(),(int)e.getY())){
                        CarPart carPart= (CarPart) part;
                        String itemId=carPart.getItemId();
                        System.out.println("###carPart.getItemId:"+itemId);
                        if(itemId==null){
                            itemId=carPart.getSprayId();
                        }else if(itemId.equals(carPart.getSprayId())){
                            itemId=carPart.getMetalId();
                        }else if(itemId.equals(carPart.getMetalId())){
                            itemId=null;
                        }
                        if(itemAll!=null){
                            if(itemAll.getSelectedId()!=null){
                                data.checkNull();
                            }
                            itemAll.setSelectedId(null);
                        }
                        carPart.setItemId(itemId);
                        System.out.println("###carPart.setItemId:"+itemId);
                        SprayItem2 item2=sprayItems2.get(carPart.getPartId());
                        item2.setSelectedId(itemId);
                        if(data!=null){
                            data.refresh();
                        }
                        break;
                    }
                }
            }

            return super.onSingleTapUp(e);
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            // e1：第1个ACTION_DOWN MotionEvent
            // e2：最后一个ACTION_MOVE MotionEvent
            // velocityX：X轴上的移动速度（像素/秒）
            // velocityY：Y轴上的移动速度（像素/秒）

            // X轴的坐标位移大于FLING_MIN_DISTANCE，且移动速度大于FLING_MIN_VELOCITY个像素/秒
            float distanceX=e2.getX()-e1.getX();

            //向右
            if (Math.abs(distanceX) > FLING_MIN_DISTANCE && Math.abs(velocityX) > FLING_MIN_VELOCITX) {
                 if(distanceX>0){
                     System.out.println("###右滑");
                     turnRight();
                 }else {
                     //右滑
                     System.out.println("###左滑");
                     turnLeft();
                 }
            }

            return super.onFling(e1, e2, velocityX, velocityY);
        }
    };


    public void showDirection(int index){
         if(index>=0&&index<mDirectionData.size()){
             mCurrentDirection=index;
             CarDirection direction=mDirectionData.get(index);
             drawDirection(direction);
         }
    }

    public void drawDirection(final CarDirection direction){
           if(mExecutor!=null&&direction!=null){
               mExecutor.execute(new Runnable() {
                   @Override
                   public void run() {
                           System.out.println("##drawDireatcion:"+direction.getClass().getName());
                           Canvas canvas=lockCanvas();
                           if(canvas!=null){
                               Bitmap bg=BitmapUtil.decodeSampledBitmapFromResources(getResources(), R.drawable.spray_car_bg,mWidth,mHeight);
                               canvas.drawBitmap(bg,0,0,mPaint);
                               bg.recycle();
                               List<ICarPart> parts=new ArrayList<>(direction);
                               boolean isAllSpray=sprayItems2.get(Constant.ID_ALL).getSelectedId()!=null;
                               for(int i=0;i<parts.size();i++){
                                   ICarPart part=parts.get(i);
                                   if(part instanceof CarBody){
                                       part.draw(getContext(),canvas,mPaint);
                                   }else if(part instanceof CarPart){
                                       CarPart carPart= (CarPart) part;
                                       if(isAllSpray){
                                           carPart.drawSpray(getContext(),canvas,mPaint);
                                       } else {
                                           SprayItem2 item2=sprayItems2.get(carPart.getPartId());
                                           if(item2!=null){
                                               carPart.setItemId(item2.getSelectedId());
                                           }
                                           if(carPart.isShow()){
                                               carPart.draw(getContext(),canvas,mPaint);
                                           }
                                       }


                                   }

                               }
                               unlockCanvasAndPost(canvas);
                           }
                       }

               });
           }
           new Thread(){
               @Override
               public void run() {
                   super.run();

               }
           }.start();

    }

    public void turnLeft(){
          int index=mCurrentDirection-1;
          if(index<0){
              index=mDirectionData.size()-1;
          }
          showDirection(index);
    }
    public void turnRight(){
        int index=mCurrentDirection+1;
        if(index>=mDirectionData.size()){
            index=0;
        }
        showDirection(index);
    }




    public void bindData(LifecycleOwner owner, SprayItemData data){
        this.data=data;
        data.observe(owner, new Observer<List<SprayItem1>>() {
            @Override
            public void onChanged(@Nullable List<SprayItem1> sprayItems) {
                   sprayItems2.clear();
                   if(sprayItems!=null){
                       for(SprayItem1 item1:sprayItems){
                           for(SprayItem2 item2:item1.getList()){
                               sprayItems2.put(item2.getId(),item2);
                           }
                       }
                   }
                   showDirection(mCurrentDirection);
            }
        });
    }

    public int getCurrentDirection() {
        return mCurrentDirection;
    }

    public void setCurrentDirection(int currentDirection) {
        mCurrentDirection = currentDirection;
    }

    public void release(){
        if(mExecutor!=null&&!mExecutor.isShutdown()){
            mExecutor.shutdownNow();
        }
    }
}
